import { createStore } from 'vuex'
import axios from 'axios'
import config from '../config'
import classModule from './modules/class' // 导入 class 模块

// 不再需要这行，因为我们已经在main.js中设置了请求拦截器
// axios.defaults.baseURL = config.apiBaseUrl

export default createStore({
  state: {
    token: localStorage.getItem('token') || '',
    userInfo: JSON.parse(localStorage.getItem('userInfo') || '{}'),
    isLoading: false,
    // 添加公告相关状态
    announcements: {
      public: [],
      all: [],
      current: null,
      totalPublic: 0,
      totalAll: 0
    },
    // 添加试题相关状态
    questions: {
      list: [],
      current: null,
      total: 0,
      filters: {
        type: '',
        difficulty: null,
        knowledgePoint: ''
      }
    }
  },
  getters: {
    isAuthenticated: state => !!state.token,
    isAdmin: state => state.userInfo.roles?.includes('ROLE_ADMIN'),
    isTeacher: state => state.userInfo.roles?.includes('ROLE_TEACHER'),
    getUserInfo: state => state.userInfo,
    // 公告相关的 getter
    publicAnnouncements: state => state.announcements.public,
    allAnnouncements: state => state.announcements.all,
    currentAnnouncement: state => state.announcements.current,
    canManageAnnouncements: state => state.userInfo.roles?.includes('ROLE_ADMIN') || state.userInfo.roles?.includes('ROLE_TEACHER'),
    // 试题相关的 getter
    allQuestions: state => state.questions.list,
    currentQuestion: state => state.questions.current,
    canManageQuestions: state => state.userInfo.roles?.includes('ROLE_ADMIN') || state.userInfo.roles?.includes('ROLE_TEACHER'),
    questionFilters: state => state.questions.filters
  },
  mutations: {
    SET_TOKEN(state, token) {
      state.token = token
      localStorage.setItem('token', token)
    },
    SET_USER_INFO(state, userInfo) {
      // 处理头像URL，确保是完整URL
      if (userInfo.avatarUrl) {
        userInfo.avatarUrl = config.getFullResourceUrl(userInfo.avatarUrl);
      } else {
        // 如果没有头像，使用空字符串，避免显示异常
        userInfo.avatarUrl = '';
      }
      
      // 使用Object.assign确保响应式更新
      state.userInfo = Object.assign({}, state.userInfo, userInfo)
      localStorage.setItem('userInfo', JSON.stringify(state.userInfo))
    },
    CLEAR_AUTH(state) {
      state.token = ''
      state.userInfo = {}
      localStorage.removeItem('token')
      localStorage.removeItem('userInfo')
    },
    SET_LOADING(state, isLoading) {
      state.isLoading = isLoading
    },
    // 公告相关的 mutations
    SET_PUBLIC_ANNOUNCEMENTS(state, { announcements, total }) {
      state.announcements.public = announcements
      state.announcements.totalPublic = total
    },
    SET_ALL_ANNOUNCEMENTS(state, { announcements, total }) {
      state.announcements.all = announcements
      state.announcements.totalAll = total
    },
    SET_CURRENT_ANNOUNCEMENT(state, announcement) {
      state.announcements.current = announcement
    },
    ADD_ANNOUNCEMENT(state, announcement) {
      if (announcement.isPublished) {
        state.announcements.public.unshift(announcement)
        state.announcements.totalPublic++
      }
      state.announcements.all.unshift(announcement)
      state.announcements.totalAll++
    },
    UPDATE_ANNOUNCEMENT(state, updatedAnnouncement) {
      // 更新all中的公告
      const indexAll = state.announcements.all.findIndex(a => a.id === updatedAnnouncement.id)
      if (indexAll !== -1) {
        state.announcements.all.splice(indexAll, 1, updatedAnnouncement)
      }
      
      // 更新public中的公告
      const indexPublic = state.announcements.public.findIndex(a => a.id === updatedAnnouncement.id)
      if (updatedAnnouncement.isPublished) {
        if (indexPublic === -1) {
          // 如果之前不在public中，需要添加并增加计数
          state.announcements.public.unshift(updatedAnnouncement)
          state.announcements.totalPublic++
        } else {
          // 如果已在public中，更新内容
          state.announcements.public.splice(indexPublic, 1, updatedAnnouncement)
        }
      } else if (indexPublic !== -1) {
        // 如果被取消发布但之前在public中，需要移除并减少计数
        state.announcements.public.splice(indexPublic, 1)
        state.announcements.totalPublic--
      }
      
      // 更新当前查看的公告
      if (state.announcements.current && state.announcements.current.id === updatedAnnouncement.id) {
        state.announcements.current = updatedAnnouncement
      }
    },
    REMOVE_ANNOUNCEMENT(state, id) {
      // 从all中移除
      const indexAll = state.announcements.all.findIndex(a => a.id === id)
      if (indexAll !== -1) {
        state.announcements.all.splice(indexAll, 1)
        state.announcements.totalAll--
      }
      
      // 从public中移除
      const indexPublic = state.announcements.public.findIndex(a => a.id === id)
      if (indexPublic !== -1) {
        state.announcements.public.splice(indexPublic, 1)
        state.announcements.totalPublic--
      }
      
      // 清除当前查看的公告
      if (state.announcements.current && state.announcements.current.id === id) {
        state.announcements.current = null
      }
    },
    // 试题相关的 mutations
    SET_QUESTIONS(state, { records, total }) {
      state.questions.list = records
      state.questions.total = total
    },
    SET_CURRENT_QUESTION(state, question) {
      state.questions.current = question
    },
    SET_QUESTION_FILTERS(state, filters) {
      state.questions.filters = { ...state.questions.filters, ...filters }
    },
    ADD_QUESTION(state, question) {
      state.questions.list.unshift(question)
      state.questions.total++
    },
    UPDATE_QUESTION(state, updatedQuestion) {
      const index = state.questions.list.findIndex(q => q.id === updatedQuestion.id)
      if (index !== -1) {
        state.questions.list.splice(index, 1, updatedQuestion)
      }
      
      // 更新当前查看的试题
      if (state.questions.current && state.questions.current.id === updatedQuestion.id) {
        state.questions.current = updatedQuestion
      }
    },
    REMOVE_QUESTION(state, id) {
      const index = state.questions.list.findIndex(q => q.id === id)
      if (index !== -1) {
        state.questions.list.splice(index, 1)
        state.questions.total--
      }
      
      // 清除当前查看的试题
      if (state.questions.current && state.questions.current.id === id) {
        state.questions.current = null
      }
    }
  },
  actions: {
    // 登录
    async login({ commit }, credentials) {
      commit('SET_LOADING', true)
      try {
        const response = await axios.post('/api/auth/login', credentials)
        if (response.data.success) {
          const { token, ...userInfo } = response.data.data
          
          // 确保头像URL是完整的，如果没有头像则设为空字符串
          if (userInfo.avatarUrl) {
            userInfo.avatarUrl = config.getFullResourceUrl(userInfo.avatarUrl);
          } else {
            userInfo.avatarUrl = '';
          }
          
          commit('SET_TOKEN', token)
          commit('SET_USER_INFO', userInfo)
        }
        return response.data
      } catch (error) {
        console.error('登录失败:', error)
        return { success: false, message: error.response?.data?.message || '登录失败，请稍后重试' }
      } finally {
        commit('SET_LOADING', false)
      }
    },
    
    // 注册
    async register({ commit }, userData) {
      commit('SET_LOADING', true)
      try {
        const response = await axios.post('/api/auth/register', userData)
        return response.data
      } catch (error) {
        console.error('注册失败:', error)
        return { success: false, message: error.response?.data?.message || '注册失败，请稍后重试' }
      } finally {
        commit('SET_LOADING', false)
      }
    },
    
    // 登出
    async logout({ commit, state }) {
      commit('SET_LOADING', true)
      try {
        if (state.token) {
          await axios.post('/api/auth/logout', null, {
            headers: { Authorization: `Bearer ${state.token}` }
          })
        }
        commit('CLEAR_AUTH')
        return { success: true, message: '已成功退出登录' }
      } catch (error) {
        console.error('登出失败:', error)
        // 即使API调用失败，也清除本地存储的令牌
        commit('CLEAR_AUTH')
        return { success: true, message: '已成功退出登录' }
      } finally {
        commit('SET_LOADING', false)
      }
    },
    
    // 获取用户信息
    async fetchUserInfo({ commit, state }) {
      if (!state.token || !state.userInfo.id) return
      
      commit('SET_LOADING', true)
      try {
        const response = await axios.get(`/api/users/${state.userInfo.id}`, {
          headers: { Authorization: `Bearer ${state.token}` }
        })
        if (response.data.success) {
          const userData = response.data.data;
          
          // 确保头像URL是完整的
          userData.avatarUrl = config.getFullResourceUrl(userData.avatarUrl);
          
          commit('SET_USER_INFO', { ...state.userInfo, ...userData })
        }
        return response.data
      } catch (error) {
        console.error('获取用户信息失败:', error)
        return { success: false, message: error.response?.data?.message || '获取用户信息失败' }
      } finally {
        commit('SET_LOADING', false)
      }
    },
    
    // 更新用户信息
    async updateUserInfo({ commit, state }, userData) {
      if (!state.token || !state.userInfo.id) return
      
      commit('SET_LOADING', true)
      try {
        const response = await axios.put(`/api/users/${state.userInfo.id}`, userData, {
          headers: { Authorization: `Bearer ${state.token}` }
        })
        if (response.data.success) {
          commit('SET_USER_INFO', { ...state.userInfo, ...userData })
        }
        return response.data
      } catch (error) {
        console.error('更新用户信息失败:', error)
        return { success: false, message: error.response?.data?.message || '更新用户信息失败' }
      } finally {
        commit('SET_LOADING', false)
      }
    },
    
    // 更新头像
    async updateAvatar({ commit, state }, avatarUrl) {
      if (!state.token || !state.userInfo.id) return
      
      commit('SET_LOADING', true)
      try {
        const response = await axios.put(`/api/users/${state.userInfo.id}/avatar?avatarUrl=${encodeURIComponent(avatarUrl)}`, null, {
          headers: { Authorization: `Bearer ${state.token}` }
        })
        if (response.data.success) {
          // 确保头像URL是完整的
          let fullAvatarUrl = response.data.data;
          
          // 检查API返回的路径是否已经符合预期格式
          if (fullAvatarUrl && !fullAvatarUrl.startsWith('/users/avatars/') && !fullAvatarUrl.startsWith('http')) {
            // 如果不是预期格式，但以/开头，可能需要移除/uploads前缀
            if (fullAvatarUrl.startsWith('/uploads/users/avatars/')) {
              fullAvatarUrl = fullAvatarUrl.replace('/uploads', '');
            }
          }
          
          fullAvatarUrl = config.getFullResourceUrl(fullAvatarUrl);
          commit('SET_USER_INFO', { ...state.userInfo, avatarUrl: fullAvatarUrl })
        }
        return response.data
      } catch (error) {
        console.error('更新头像失败:', error)
        return { success: false, message: error.response?.data?.message || '更新头像失败' }
      } finally {
        commit('SET_LOADING', false)
      }
    },
    
    // 更改密码
    async changePassword({ commit, state }, passwordData) {
      if (!state.token || !state.userInfo.id) return
      
      commit('SET_LOADING', true)
      try {
        const response = await axios.put(`/api/users/${state.userInfo.id}/password`, passwordData, {
          headers: { Authorization: `Bearer ${state.token}` }
        })
        return response.data
      } catch (error) {
        console.error('更改密码失败:', error)
        return { success: false, message: error.response?.data?.message || '更改密码失败' }
      } finally {
        commit('SET_LOADING', false)
      }
    },
    
    // 获取公开公告列表
    async fetchPublicAnnouncements({ commit }, { page = 1, size = 10 }) {
      commit('SET_LOADING', true)
      try {
        const response = await axios.get(`/api/announcements/public?page=${page}&size=${size}`)
        if (response.data.success) {
          commit('SET_PUBLIC_ANNOUNCEMENTS', {
            announcements: response.data.data.announcements,
            total: response.data.data.total
          })
        }
        return response.data
      } catch (error) {
        console.error('获取公开公告失败:', error)
        return { success: false, message: error.response?.data?.message || '获取公开公告失败' }
      } finally {
        commit('SET_LOADING', false)
      }
    },
    
    // 获取所有公告（管理员/教师）
    async fetchAllAnnouncements({ commit, state }, { page = 1, size = 10, status = null }) {
      if (!state.token) return
      
      commit('SET_LOADING', true)
      try {
        let url = `/api/announcements?page=${page}&size=${size}`
        if (status !== null) {
          url += `&status=${status}`
        }
        
        const response = await axios.get(url, {
          headers: { Authorization: `Bearer ${state.token}` }
        })
        
        if (response.data.success) {
          commit('SET_ALL_ANNOUNCEMENTS', {
            announcements: response.data.data.announcements,
            total: response.data.data.total
          })
        }
        return response.data
      } catch (error) {
        console.error('获取所有公告失败:', error)
        return { success: false, message: error.response?.data?.message || '获取所有公告失败' }
      } finally {
        commit('SET_LOADING', false)
      }
    },
    
    // 获取公告详情
    async fetchAnnouncementDetail({ commit, state }, id) {
      commit('SET_LOADING', true)
      try {
        const headers = state.token ? { Authorization: `Bearer ${state.token}` } : {}
        const response = await axios.get(`/api/announcements/${id}`, { headers })
        
        if (response.data.success) {
          commit('SET_CURRENT_ANNOUNCEMENT', response.data.data)
        }
        return response.data
      } catch (error) {
        console.error('获取公告详情失败:', error)
        
        // 针对403权限错误提供友好的错误消息
        if (error.response?.status === 403) {
          return { 
            success: false, 
            message: '权限不足，请登录后查看此公告' 
          }
        }
        
        // 针对404错误
        if (error.response?.status === 404) {
          return { 
            success: false, 
            message: '公告不存在或已被删除' 
          }
        }
        
        // 其他错误
        return { 
          success: false, 
          message: error.response?.data?.message || '获取公告详情失败，请稍后重试' 
        }
      } finally {
        commit('SET_LOADING', false)
      }
    },
    
    // 创建公告
    async createAnnouncement({ commit, state }, { announcement, files }) {
      if (!state.token) return { success: false, message: '未登录或 token 已过期' }
      
      commit('SET_LOADING', true)
      try {
        const formData = new FormData()
        formData.append('announcement', new Blob([JSON.stringify(announcement)], {
          type: 'application/json'
        }))
        
        if (files && files.length > 0) {
          files.forEach(file => {
            formData.append('files', file)
          })
        }

        const response = await axios.post('/api/announcements', formData, {
          headers: {
            'Authorization': `Bearer ${state.token}`,
            'Content-Type': 'multipart/form-data'
          }
        })

        if (response.data.success) {
          commit('ADD_ANNOUNCEMENT', response.data.data)
          return { success: true }
        }
        return { success: false, message: response.data.message || '创建失败' }
      } catch (error) {
        console.error('创建公告失败:', error)
        return { 
          success: false, 
          message: error.response?.status === 403 ? '没有权限执行此操作' : (error.response?.data?.message || '创建公告失败')
        }
      } finally {
        commit('SET_LOADING', false)
      }
    },
    
    // 更新公告
    async updateAnnouncement({ commit, state }, { id, announcement }) {
      if (!state.token) return
      
      commit('SET_LOADING', true)
      try {
        const response = await axios.put(`/api/announcements/${id}`, announcement, {
          headers: { Authorization: `Bearer ${state.token}` }
        })
        
        if (response.data.success) {
          commit('UPDATE_ANNOUNCEMENT', response.data.data)
        }
        return response.data
      } catch (error) {
        console.error('更新公告失败:', error)
        return { success: false, message: error.response?.data?.message || '更新公告失败' }
      } finally {
        commit('SET_LOADING', false)
      }
    },
    
    // 删除公告
    async deleteAnnouncement({ commit, state }, id) {
      if (!state.token) return
      
      commit('SET_LOADING', true)
      try {
        const response = await axios.delete(`/api/announcements/${id}`, {
          headers: { Authorization: `Bearer ${state.token}` }
        })
        
        if (response.data.success) {
          commit('REMOVE_ANNOUNCEMENT', id)
        }
        return response.data
      } catch (error) {
        console.error('删除公告失败:', error)
        return { success: false, message: error.response?.data?.message || '删除公告失败' }
      } finally {
        commit('SET_LOADING', false)
      }
    },
    
    // 发布/取消发布公告
    async togglePublishAnnouncement({ commit, state }, { id, isPublished }) {
      if (!state.token) return
      
      commit('SET_LOADING', true)
      try {
        const response = await axios.put(`/api/announcements/${id}/publish?isPublished=${isPublished}`, null, {
          headers: { Authorization: `Bearer ${state.token}` }
        })
        
        if (response.data.success) {
          commit('UPDATE_ANNOUNCEMENT', response.data.data)
        }
        return response.data
      } catch (error) {
        console.error('更改公告发布状态失败:', error)
        return { success: false, message: error.response?.data?.message || '更改公告发布状态失败' }
      } finally {
        commit('SET_LOADING', false)
      }
    },
    
    // 获取试题列表
    async fetchQuestions({ commit, state }, { page = 1, size = 10, type = '', difficulty = null, knowledgePoint = '' }) {
      if (!state.token) return
      
      commit('SET_LOADING', true)
      try {
        let url = `/api/questions/page?page=${page}&size=${size}`
        
        if (type) {
          url += `&type=${type}`
        }
        
        if (difficulty !== null) {
          url += `&difficulty=${difficulty}`
        }
        
        if (knowledgePoint) {
          url += `&knowledgePoint=${encodeURIComponent(knowledgePoint)}`
        }
        
        const response = await axios.get(url, {
          headers: { Authorization: `Bearer ${state.token}` }
        })
        
        if (response.data.success) {
          commit('SET_QUESTIONS', {
            records: response.data.data.records,
            total: response.data.data.total
          })
          commit('SET_QUESTION_FILTERS', { type, difficulty, knowledgePoint })
        }
        
        return response.data
      } catch (error) {
        console.error('获取试题列表失败:', error)
        return { success: false, message: error.response?.data?.message || '获取试题列表失败' }
      } finally {
        commit('SET_LOADING', false)
      }
    },
    
    // 获取试题详情
    async fetchQuestionDetail({ commit, state }, id) {
      if (!state.token) return
      
      commit('SET_LOADING', true)
      try {
        const response = await axios.get(`/api/questions/${id}`, {
          headers: { Authorization: `Bearer ${state.token}` }
        })
        
        if (response.data.success) {
          commit('SET_CURRENT_QUESTION', response.data.data)
        }
        
        return response.data
      } catch (error) {
        console.error('获取试题详情失败:', error)
        return { success: false, message: error.response?.data?.message || '获取试题详情失败' }
      } finally {
        commit('SET_LOADING', false)
      }
    },
    
    // 创建试题
    async createQuestion({ commit, state }, question) {
      if (!state.token) return
      
      commit('SET_LOADING', true)
      try {
        const response = await axios.post('/api/questions', question, {
          headers: { Authorization: `Bearer ${state.token}` }
        })
        
        if (response.data.success) {
          commit('ADD_QUESTION', response.data.data)
        }
        
        return response.data
      } catch (error) {
        console.error('创建试题失败:', error)
        return { success: false, message: error.response?.data?.message || '创建试题失败' }
      } finally {
        commit('SET_LOADING', false)
      }
    },
    
    // 更新试题
    async updateQuestion({ commit, state }, { id, question }) {
      if (!state.token) return
      
      commit('SET_LOADING', true)
      try {
        const response = await axios.put(`/api/questions/${id}`, question, {
          headers: { Authorization: `Bearer ${state.token}` }
        })
        
        if (response.data.success) {
          commit('UPDATE_QUESTION', response.data.data)
        }
        
        return response.data
      } catch (error) {
        console.error('更新试题失败:', error)
        return { success: false, message: error.response?.data?.message || '更新试题失败' }
      } finally {
        commit('SET_LOADING', false)
      }
    },
    
    // 删除试题
    async deleteQuestion({ commit, state }, id) {
      if (!state.token) return
      
      commit('SET_LOADING', true)
      try {
        const response = await axios.delete(`/api/questions/${id}`, {
          headers: { Authorization: `Bearer ${state.token}` }
        })
        
        if (response.data.success) {
          commit('REMOVE_QUESTION', id)
        }
        
        return response.data
      } catch (error) {
        console.error('删除试题失败:', error)
        return { success: false, message: error.response?.data?.message || '删除试题失败' }
      } finally {
        commit('SET_LOADING', false)
      }
    },
    
    // 批量导入试题
    async batchImportQuestions({ commit, state }, questions) {
      if (!state.token) return
      
      commit('SET_LOADING', true)
      try {
        const response = await axios.post('/api/questions/batch', questions, {
          headers: { Authorization: `Bearer ${state.token}` }
        })
        
        return response.data
      } catch (error) {
        console.error('批量导入试题失败:', error)
        return { success: false, message: error.response?.data?.message || '批量导入试题失败' }
      } finally {
        commit('SET_LOADING', false)
      }
    },

    // --- 新增: 根据ID获取用户信息 ---
    async fetchUserById(_, userId) {
        // 这里不设置全局 loading，避免干扰其他操作
        // commit('SET_LOADING', true)
        try {
            const response = await axios.get(`/api/users/${userId}`);
            if (response.data.success) {
                // 只返回数据，不存入全局 state
                return response.data.data;
            } else {
                console.error('获取用户信息失败 (by ID):', response.data.message);
                return null;
            }
        } catch (error) {
            console.error('获取用户信息失败 (by ID):', error);
            return null;
        } finally {
            // commit('SET_LOADING', false)
        }
    },

    // --- 移除: 搜索用户 ---
    // async searchUsers(_, query) {
    //     // 这里不设置全局 loading
    //     try {
    //         const response = await axios.get(`/api/users/search?query=${encodeURIComponent(query)}`);
    //         if (response.data.success) {
    //             // 返回搜索结果列表
    //             return response.data.data; // 假设返回 { success: true, data: [...] }
    //         } else {
    //             console.error('搜索用户失败:', response.data.message);
    //             return [];
    //         }
    //     } catch (error) {
    //         console.error('搜索用户失败:', error);
    //         return [];
    //     }
    // },
    // --- 结束移除 ---
  },
  modules: {
    class: classModule // 注册 class 模块
  }
}) 